﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using BLToolkit.ComponentModel;
using ComponentFactory.Krypton.Toolkit;
using LED_Utils.MultitrackControl;

namespace CustomDataBindingControl
{
	public partial class FrameViewControl : UserControl
	{
		public FrameViewControl()
		{
			InitializeComponent();
			SetStyle(ControlStyles.Selectable, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer , true);
            SetStyle(ControlStyles.AllPaintingInWmPaint , true);
           // SetStyle(ControlStyles.UserPaint , false);
            GdiHelper.SetDoubleBuffer(this, true);

            BorderThickness = 1;
		}

        public object _dataSource;

        public object DataSource
        {
            get
            {
                return _dataSource;
            }
            set
            {
                _dataSource = value;
            }
        }

        private void SetValue(string property, object value)
        {
            if (_dataSource == null)
                return;
            if (_dataSource is DataRowView)
            {
                ((DataRowView)_dataSource).Row.SetField(property, value);
            }
            else
            {
                _dataSource.GetType().GetProperty(property).SetValue(_dataSource, value, null);
            }
        }

		//public string LeftString   { get { return label1.Text; } set { label1.Text = value; } }
		//public string RightString  { get { return label2.Text; } set { label2.Text = value; } }
		//public string CenterString { get { return textBox1.Text; } set { textBox1.Text = value; } }
		//public Color Color { get { return textBox1.Text; } set { textBox1.Text = value; } }
        private float _frameWidth;
		public float FrameWidth {
			get{return _frameWidth;}
			set
			{
				if (value != _frameWidth)
				{

					_frameWidth = value;
                    _internalSizeChange = true;
                    Size = new Size((int)((double)_frameWidth * ((double)ScaleFactor / (double)100)), Size.Height);
                    //Binding frameWidthBinding = this.DataBindings["FrameWidth"];
                    //if (frameWidthBinding != null)
                    //{
                    //    frameWidthBinding.WriteValue();
                    //    //row.Row["FrameWidth"] = _frameWidth;
                    //    //((PropertyManager)frameWidthBinding.BindingManagerBase).EndCurrentEdit(); 
                    //}
                    SetValue("FrameDuration", _frameWidth);
                    _internalSizeChange = false;

					OnFrameWidthChanged();
				}
			}
		}
        private bool _internalSizeChange = false;

        public event EventHandler FrameWidthChanged;
        protected void OnFrameWidthChanged()
        {
            if (FrameWidthChanged != null)
            {
                FrameWidthChanged(this, EventArgs.Empty);
            }
        }

        private Color _startColor;
        [Bindable(BindableSupport.Yes)]
        public Color StartColor
        {
            get { return _startColor; }
            set
            {
                if (value.ToArgb () != _startColor.ToArgb ())
                {
                    _startColor = value;
                    SetValue("StartColor", _startColor);
                    Invalidate();
                    OnStartColorChanged();
                }
            }
        }

        public event EventHandler StartColorChanged;
        private void OnStartColorChanged()
        {
            if (StartColorChanged != null)
            {
                StartColorChanged(this, EventArgs.Empty);
            }
        }

        private Color _endColor;

        [Bindable(BindableSupport.Yes)]
        public Color EndColor
        {
            get { return _endColor; }
            set
            {
                if (value.ToArgb() != _endColor.ToArgb ())
                {
                    _endColor = value;
                    SetValue("EndColor", _endColor);
                    Invalidate();
                    OnEndColorChanged();
                }
            }
        }

        public event EventHandler EndColorChanged;
        private void OnEndColorChanged()
        {
            if (EndColorChanged != null)
            {
                EndColorChanged(this, EventArgs.Empty);
            }
        }

        public bool Scaling { get; set; }
        public int ScaleFactor { get { return TrackEditorControl.ScalePercents; } } 

        protected override void  OnSizeChanged(EventArgs e)
        {
 	         base.OnSizeChanged(e);
             if (_internalSizeChange)
                 return;
             if (Scaling )
                 return;
             this.FrameWidth = (int)((double)Size.Width / ((double)ScaleFactor / (double)100));
            
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (_internalSizeChange)
                return;
            if (Scaling)
                return;
            if (_isRightSplitterClicked)
                return;
            
            this.FrameWidth = (int)((double)Size.Width / ((double)ScaleFactor / (double)100));
        } 

        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            base.OnMouseDoubleClick(e);
            Point clickPoint = e.Location;
            if (clickPoint.X < this.Width / 2)
            {
                ShowFrameEditor(FrameEditorForm2.State.StartColor);
            }
            else
            {
                ShowFrameEditor(FrameEditorForm2.State.EndColor);
            }
        }

        public void ShowFrameEditor(FrameEditorForm2.State state)
        {
            FrameEditorForm2 form = new FrameEditorForm2();
            form.StartColor = StartColor;
            form.EndColor   = EndColor;
            form.InitState  = state;
            DialogResult result = form.ShowDialog();
            if (result != DialogResult.OK)
                return;

            StartColor = form.StartColor;
            EndColor = form.EndColor;
        } 



        

		

		protected override void OnPaintBackground(PaintEventArgs e)
		{
			base.OnPaintBackground(e);
            //e.ClipRectangle. 
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            //Brush brush = new LinearGradientBrush(e.ClipRectangle, StartColor, EndColor, LinearGradientMode.Horizontal);     
            //e.Graphics.FillRectangle(brush,e.ClipRectangle);
            

            Rectangle rect = ClientRectangle;
            if (Selected)
            {
                using (Brush brush = new LinearGradientBrush(rect, Color.White, Color.Silver, LinearGradientMode.Vertical))
                {
                    e.Graphics.FillRectangle(brush, rect);
                }
            }
            int customPadding = rect.Height / 5;

            Point topLeft = new Point(rect.Location.X, rect.Location.Y + customPadding);
            Point bottomLeft = new Point(rect.Location.X, rect.Location.Y + rect.Height - customPadding);

            Point topRight = new Point(rect.Location.X + rect.Width, rect.Location.Y + customPadding);
            Point bottomRight = new Point(rect.Location.X + rect.Width, rect.Location.Y + rect.Height - customPadding);

            if (StartColor.ToArgb() != EndColor.ToArgb())
            {
                Brush brushStart = new SolidBrush(StartColor);
                Brush brushEnd = new SolidBrush(EndColor);
                e.Graphics.FillPolygon(brushStart, new Point[] { topLeft, topRight, bottomLeft, topLeft });
                e.Graphics.FillPolygon(brushEnd, new Point[] { bottomLeft, topRight, bottomRight, bottomLeft });
                
                Pen black = new Pen(Color.Black, 1);
                e.Graphics.DrawLine(black, bottomLeft, topRight);
            }
            else
            {
                Brush brushStart = new SolidBrush(StartColor);
                e.Graphics.FillRectangle(brushStart, topLeft.X, topLeft.Y, rect.Width,rect.Height - 2 * customPadding );
            }

            Pen blackPen = new Pen(Color.Black , BorderThickness);
            e.Graphics.DrawLine(blackPen, new Point(rect.Location.X + rect.Width - BorderThickness, rect.Location.Y), new Point(rect.Location.X + rect.Width - BorderThickness, rect.Location.Y + rect.Height));
            e.Graphics.DrawLine(blackPen, topLeft,topRight);
            e.Graphics.DrawLine(blackPen, bottomLeft , bottomRight);



        }
        private bool _selected;
        public bool Selected
        {
            get { return _selected; }
            set
            {
                _selected = value;
                if (_selected)
                {
                    Select();
                    Focus(); 

                }
                Invalidate();
            }
        }

        public int BorderThickness { get; set; }

		private void textBox1_TextChanged(object sender, EventArgs e)
		{
			//BindingContext ctx  = BindingContext;
			//Binding b = DataBindings["RightString"];
			//PropertyManager pm = (PropertyManager)BindingContext[this];
			//pm.
			//b.
			//OnCenterStringChanged();
		}

		protected override void Select(bool directed, bool forward)
		{
			//textBox1.Select();  
			//base.Select(directed, forward);
		}
        bool _isRightSplitterClicked;
        int _initialRightSplitterScreenCoordinatesX;
        int _initialWidth;
        int assignWidthCount = 0;

        int _currentRightSplitterScreenCoordinatesX;

        protected override void OnMouseMove (MouseEventArgs e)
        {
            base.OnMouseMove(e); 

            if (e.Location.X > this.Width -10)
            {
                Cursor = Cursors.SizeWE ;
            }
            else
            {
                Cursor = Cursors.Hand;
            }
            if (_isRightSplitterClicked)
            {
                Point screenPoint = MousePosition; //this.PointToScreen(e.Location);
                if (_currentRightSplitterScreenCoordinatesX == screenPoint.X)
                    return;

                _currentRightSplitterScreenCoordinatesX = screenPoint.X;

                int preCalculatedWidth = _initialWidth + (_currentRightSplitterScreenCoordinatesX - _initialRightSplitterScreenCoordinatesX);
                if (preCalculatedWidth == Width || preCalculatedWidth < 0)
                    return;
                this.Width = preCalculatedWidth;
                assignWidthCount += 1;
                //label1.Text = string.Format("{5}| Width:{0}, Left:{1}, X1:{2}, X2:{3}, Delta:{4}", this.Width, this.Left, screenPoint.X, _initialRightSplitterScreenCoordinatesX, screenPoint.X - _initialRightSplitterScreenCoordinatesX, assignWidthCount);
            }
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e); 

            if (e.Location.X > this.Width - 10)
            {
                _isRightSplitterClicked = true;
                //Cursor = Cursors.VSplit; 
                Point screenPoint = MousePosition; 
                _initialRightSplitterScreenCoordinatesX = screenPoint.X;
                _initialWidth = Width;
                assignWidthCount = 0;
            }

        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e); 
            _isRightSplitterClicked = false;
            //Cursor = Cursors.Default; 

        }

        private void kryptonPanel1_Enter(object sender, EventArgs e)
        {
            OnEnter(e);
        }

        private void kryptonPanel1_Click(object sender, EventArgs e)
        {
            OnEnter(e);
        }

        private void FrameViewControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                OnFrameDeleting(); 
            }
        }

        public event EventHandler FrameDeleting;
        protected virtual void OnFrameDeleting()
        {
            if (FrameDeleting != null)
            {
                FrameDeleting(this, EventArgs.Empty);
            }

        }

        //public PaletteBack StateCommon { get { return kryptonPanel1.StateCommon; } }
        //public PaletteBack StateNormal { get { return kryptonPanel1.StateNormal; } }



	}
}
